<script lang="ts" setup name="productRecommendEdit">
import HeaderCard from "./components/HeaderCard.vue";
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { FormData } from "@/types/createActivity";
import { recommendFormList } from "@/types/createActivity";
import { getGoodsList, getFoodCategoryList } from "@/api/modules/goods";
import { createRecommendActivityAPI, getRecommendActivityDetailAPI, editRecommendActivityAPI } from "@/api/modules/activity";
import SelectTreeData from "@/components/SelectTreeData/index.vue";
import { ElForm, ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();

const recommendRef = ref<InstanceType<typeof ElForm> | null>(null);
const recommendFormData = reactive<recommendFormList>({
  path: "/marketing/product-recommend?id=",
  name: "",
  id: 0,
  // activityType?: number,
  code: "",
  desc: "",
  type: 6, // 菜品推荐6
  rule: {
    list: [
      {
        mainFoodList: [],
        recommendList: []
      }
    ]
  },
  cycleType: 0, //  0.每天；1.周（周一至周日);2.月（1-31号)
  cycleValue: [],
  validityRange: [new Date().toLocaleString(), new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toLocaleString()],
  promotionType: 1 // 1营销活动 2餐饮促销活动
});
const rules = reactive({
  name: [{ required: true, message: "请输入活动名称" }],
  cycleValue: [{ required: true, message: "请选择可用周期" }],
  validityRange: [{ required: true, message: "请选择可用日期" }]
});
const addGroup = () => {
  recommendFormData.rule.list.push({
    mainFoodList: [],
    recommendList: []
  });
};

const cycleData = reactive([
  { label: "星期一", value: 1 },
  { label: "星期二", value: 2 },
  { label: "星期三", value: 3 },
  { label: "星期四", value: 4 },
  { label: "星期五", value: 5 },
  { label: "星期六", value: 6 },
  { label: "星期日", value: 7 }
]);

// 选择主菜配菜
const SelectTreeDataRef = ref<InstanceType<typeof SelectTreeData> | null>(null);
const openProductDialog = (item, index, type) => {
  SelectTreeDataRef.value.acceptParams({
    title: "选择菜品",
    idName: "foodCategoryId",
    isView: false,
    index,
    type,
    mate: "id",
    apiParams: { isDefault: type === "main" ? 1 : 0 },
    selTags:
      type === "main"
        ? recommendFormData.rule.list[index].mainFoodList.map(v => {
            v.id = v.foodId;
            v.name = v.name;
            return v;
          })
        : recommendFormData.rule.list[index].recommendList.map(v => {
            v.id = v.foodId;
            v.name = v.name;
            return v;
          }),
    columns: [
      { type: "selection", label: "#", width: 60 },
      { prop: "name", label: "菜品名称", align: "left" },
      { prop: "foodSpecName", label: "量", align: "left" },
      { prop: "foodTypeName", label: "分类", align: "left" }
    ],
    api: getGoodsList,
    treeApi: getFoodCategoryList
  });
};
const onSelectedList = (e: any) => {
  if (e.type === "main") {
    recommendFormData.rule.list[e.index].mainFoodList = JSON.parse(
      JSON.stringify(e.list.map((v: any) => ({ name: v.name, foodId: v.id, foodSpecId: v.foodSpecId })))
    );
  } else {
    recommendFormData.rule.list[e.index].recommendList = JSON.parse(
      JSON.stringify(e.list.map((v: any) => ({ name: v.name, foodId: v.id, foodSpecId: v.foodSpecId, posPrice: v.posPrice })))
    );
  }
};

// 选择其他日期时先设置为空
const onChangeCycleType = () => {
  recommendFormData.cycleValue = [];
};

// 删除组合
const onDelGroup = (index: number) => {
  if (recommendFormData.rule.list.length <= 1) return ElMessage({ message: "至少保留一项", type: "warning" });
  recommendFormData.rule.list.splice(index, 1);
};

// 删除主菜
const onClose = (item: any, i: number, type: string, index: number) => {
  if (type === "main") {
    if (recommendFormData.rule.list[index].mainFoodList.length <= 1)
      return ElMessage({ message: "至少保留一项", type: "warning" });

    recommendFormData.rule.list[index].mainFoodList.splice(i, 1);
  } else {
    if (recommendFormData.rule.list[index].recommendList.length <= 1)
      return ElMessage({ message: "至少保留一项", type: "warning" });
    recommendFormData.rule.list[index].recommendList.splice(i, 1);
  }
};

// 获取数据
onMounted(async () => {
  if (route.query.id) {
    const res: any = await getRecommendActivityDetailAPI({ id: route.query.id });
    Object.keys(recommendFormData).forEach(key => {
      if (res.data.hasOwnProperty(key)) {
        recommendFormData[key] = res.data[key];
      }
    });
  }
});

// 提交数据
const onSubmit = async () => {
  await recommendRef.value!.validate();
  if (route.query.id) {
    await editRecommendActivityAPI(recommendFormData);
  } else {
    await createRecommendActivityAPI(recommendFormData);
  }
  router.push("/marketing/coupon-scan?upList=" + true);
};
</script>

<template>
  <div class="productRecommendEdit-box">
    <HeaderCard
      :is-show-button="route.query.type === 'view' ? false : true"
      @back="router.go(-1)"
      @confirm="onSubmit"
      title="菜品推荐活动"
    ></HeaderCard>

    <div class="main">
      <el-row style="height: 100%">
        <el-col style="height: 100%" :span="5">
          <img style="width: 96%; height: 90%" src="@/assets/images/recommend.png" alt="" />
        </el-col>
        <el-col :span="19" style="height: 100%">
          <el-form
            style="height: 96%; padding: 20px; overflow-y: auto"
            ref="recommendRef"
            :rules="rules"
            :model="recommendFormData"
            label-width="140"
            label-position="left"
          >
            <div style="width: 45%">
              <el-form-item label="活动名称" prop="name">
                <el-input v-model="recommendFormData.name" placeholder="请输入活动名称"></el-input>
              </el-form-item>
              <el-form-item prop="code" label="活动编码">
                <el-input v-model="recommendFormData.code" placeholder="请输入活动编码"></el-input>
              </el-form-item>
              <el-form-item prop="promotionType" label="活动类型">
                <el-select v-model="recommendFormData.promotionType">
                  <el-option :value="1" label="营销活动" />
                  <el-option :value="2" label="菜品促销活动" />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="展示位置">
            <el-checkbox-group v-model="checkList">
              <el-checkbox label="点餐页" value="orderFoods" />
              <el-checkbox label="菜品详情页" value="productDetail" />
              <el-checkbox label="下单页" value="placeOrder" />
            </el-checkbox-group>
          </el-form-item> -->
              <el-form-item label="自定义可用日期" prop="validityRange">
                <el-date-picker
                  format="YYYY-MM-DD"
                  v-model="recommendFormData.validityRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>

              <el-form-item label="可用日期" prop="cycleType">
                <el-radio-group v-model="recommendFormData.cycleType" @change="onChangeCycleType">
                  <el-radio :value="0" size="large">每天</el-radio>
                  <el-radio :value="1" size="large">每周</el-radio>
                  <el-radio :value="2" size="large">每月</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                label=""
                prop="cycleValue"
                v-if="recommendFormData.cycleType === 1"
                :rules="recommendFormData.cycleType === 1 ? rules.cycleValue : [{ required: false }]"
              >
                <div class="select-day-in-week-wrapper">
                  <el-checkbox-group v-model="recommendFormData.cycleValue">
                    <el-checkbox v-for="cycle in cycleData" :key="cycle.value" :value="cycle.value">{{
                      cycle.label
                    }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
              <el-form-item
                label=""
                prop="cycleValue"
                v-if="recommendFormData.cycleType === 2"
                :rules="recommendFormData.cycleType === 2 ? rules.cycleValue : [{ required: false }]"
              >
                <div class="select-day-in-week-wrapper">
                  <el-checkbox-group v-model="recommendFormData.cycleValue">
                    <el-checkbox v-for="day in 31" :key="'day' + day" :value="day">{{ day < 10 ? "0" + day : day }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </div>

            <div class="match-content">
              <div class="recommend-combination mt20" v-for="(item, index) in recommendFormData.rule.list" :key="index">
                <div class="title">
                  <div>推荐组合{{ index + 1 }}:</div>
                  <div class="flx-default" style="cursor: pointer" @click="onDelGroup(index)">
                    <el-icon><CircleClose /></el-icon>
                    <span class="ml5">删除组合</span>
                  </div>
                </div>
                <div class="pl30 pr30 pt10">
                  <div class="fsize14">顾客购买以下菜品</div>
                  <div class="mt10 padding5" style="background-color: #fafafa">
                    <el-button type="primary" size="small" @click="openProductDialog(item, index, 'main')">添加主菜</el-button>
                    <span class="fsize12 ml10" style="color: #999394">已选{{ item.mainFoodList.length }}个</span>
                  </div>
                  <div style="height: 30px; overflow: auto; border: 1px solid #eeeeee" class="flx-default padding5">
                    <!-- <el-tag 
                type="info" 
                closable 
                class="mr10"
                 v-for="(v, index) in 20" 
                 :key="index" 
                 @close="onClose">
                 
                 <el-tag> -->

                    <el-tag
                      type="info"
                      v-for="(v, i) in item.mainFoodList"
                      :key="i"
                      class="mr10"
                      closable
                      @close="onClose(v, i, 'main', index)"
                    >
                      {{ v.name }}
                    </el-tag>
                  </div>

                  <div class="fsize14 mt20">将自动推荐以下菜品</div>
                  <div class="mt10 padding5" style="background-color: #fafafa">
                    <el-button type="primary" size="small" @click="openProductDialog(item, index, 'recommend')">
                      添加推荐菜
                    </el-button>
                    <span class="fsize12 ml10" style="color: #999394">最多选择选6个推荐菜</span>
                  </div>
                  <!-- <div style="height: 30px; border: 1px solid #eeeeee" class="padding5 mt10"></div> -->
                  <!-- 表格 -->
                  <el-table class="mb20 mt20" :data="item.recommendList">
                    <el-table-column label="序号" width="80">
                      <template #default="{ $index }">
                        <div>{{ $index + 1 }}</div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="菜品名称" />
                    <el-table-column prop="posPrice" label="菜品价格" />
                    <el-table-column label="操作" width="200">
                      <template #default="{ row, $index }">
                        <el-button type="text" @click="onClose(row, $index, 'recommend', index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

              <div class="pl20 mt20 mb40 flx-default" style="line-height: 50px; border: 1px dashed #d9d9d9">
                <el-icon color="#fc9a22"><CirclePlus /></el-icon>
                <span class="ml6" style="color: #fc9a22" @click="addGroup">新增推荐组合</span>
                <span class="ml10" style="color: #777777">最多30个</span>
              </div>
            </div>
          </el-form>
        </el-col>
      </el-row>

      <SelectTreeData ref="SelectTreeDataRef" @selected-list="onSelectedList"></SelectTreeData>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.productRecommendEdit-box {
  height: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .main {
    width: 100%;
    height: calc(100% - 72px);
    padding: 20px;
    overflow: hidden;
    .match-content {
      box-sizing: border-box;
      width: 70%;
      .recommend-combination {
        border: 1px solid #e8e8e8;
        border-radius: 5px;
        .title {
          display: flex;
          justify-content: space-between;
          padding: 0 20px;
          line-height: 40px;
          color: #7f786c;
          border-bottom: 1px solid #e8e8e8;
        }
      }
    }
  }
}
</style>
